// promise有三种状态
//1.pending 等待 2.fufilled 成功 3.rejected失败

// const myPromise = new Promise((resolve, reject) => {
//     //异步调用代码，成功时调用resolve,失败调用reject

// })


//手写promise
function myPromise(executor) {
    let self = this;
    //初始化Promise的状态和结果
    self.status = 'pending';
    self.value = undefined;

    //定义Promise的成功和失败的回调函数
    self._callbacks = [];

    //定义resolve
    const resolve = value => {
        if(self.status === 'pending') {
            self.status = 'fulfilled';
            self.value = value;

            //执行成功的回调函数
            self._callbacks.forEach(
                callback => callback.onFulfilled(value)
            );
        }
    }

    //定义reject函数，用于将primise的状态从pending改变为rejected
    const reject = resion => {
        if(self.status === 'pedding') {
            self.status = 'rejected';
            self.value = resion;

            //执行失败的回调函数
            self._callbacks.forEach(
                callback => callback.onRejected(resion)
            )
        }
    }

    //执行executor函数,传入resolve和reject
    try{
        executor(resolve, reject);
    } catch(e) {
        reject(e);
    }
}

myPromise.prototype.then = function(onFulfilled, onRejected) {
    if(this.status === 'fulfilled') {
        onFulfilled(this.value);
    } else if(this.status === 'rejected') {
        onRejected(this.value);
    } else if(this.status === 'pending') {
        this._callbacks.push({
            onFulfilled: onFulfilled,
            onRejected: onRejected
        })
    }
}


const Promise = new myPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('success');
    }, 1000)
})

Promise.then(value => {
    console.log(value);
}, resion => {
    console.log(resion);
})
